// pages/fillOrder/fillOrder.js
const app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    // index: '',
    // index: 0,
    isFreeSend: true, // 起送
    isPaid: false,
    userInfo: null,
    orderData: null, // 订单数据
    options: null, //应该是立即购买时使用的变量，传递数据信息
    user_note: {}, //订单备注
    computeData: null, // 计算价格数据
    tickets: [], //优惠券数据
    popup: [], //应该是记录优惠券是否选中的变量
    couponCode: '', // 优惠券码
    coupon_id: {}, // 优惠券ID
    sm: 0, // 配送方式
    action: 'buy_now',
    cart_form_data: [],
    getGoodsTypes: [{
        id: 0,
        value: '快递',
        checked: true,
        isShow: true
      },
      {
        id: 1,
        value: '自提',
        checked: false,
        isShow: true
      },
    ],
    submit: 1,
    iseduitadd: true //好像是标识是否是从添加地址页跳转回来的
  },


  // 修改配送方式
  radioChange(e) {
    const that = this;
    if (e.detail.value == 1) {
      if (app.globalData.userInfo.mobile == '') {
        wx.redirectTo({
          url: '/page/tabBar/bindphone/bindphone',
        })
        return;
      }
    }
    that.setData({
      sm: e.detail.value
    })
    that.getCompute();
  },

  // 重新选择地址
  toAddresslist(e) {
    let where = e.currentTarget.dataset.where;
    wx.navigateTo({
      url: `/page/detail/pages/addresslist/addresslist?where=${where}`,
    })
  },

  // 切换弹出优惠券
  userTickets(e) {
    const that = this;
    let index = e.currentTarget.dataset.index;
    that.setData({
      [`popup[${index}]`]: !that.data.popup[index]
    })
  },


  // 获取计算价格等数据
  getCompute(e) {
    const that = this;
    let cart_form_data = {
      user_note: that.data.user_note,
      coupon_id: that.data.coupon_id
    }
    let json = {
      token: app.globalData.token,
      address_id: that.data.orderData.addressList.address_id,
      sm: that.data.sm,
      cart_form_data: JSON.stringify(cart_form_data),
      action: that.data.action,
      goods_id: that.data.action == "buy_now" ? that.data.options.goodsid : "",
      goods_num: that.data.action == "buy_now" ? that.data.options.goodsnum : "",
      type: "miniapp",
    }
    let jsonData = app.utils.getSignData(json);

    that.setData({
      hiddenLoading: false
    })
    app.utils.post(app.api.reqUrls.submitOrder, jsonData).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        let values = [];
        for (let i in res.result.store_list_pay_info) {
          values.push(res.result.store_list_pay_info[i])
        }
        res.result.store_list_pay_info = values;
        that.setData({
          computeData: res.result,
        })
      } else if (res.status == -11) {
        wx.showModal({
          content: res.msg,
          confirmText: '确定',
          confirmColor: '#ff5151',
          success(e) {
            if (e.confirm) {
              wx.navigateTo({
                url: `/page/detail/pages/addresslist/addresslist?where=fillOrder`,
              })
            }
          }
        })
      } else {
        throw res.msg;
      }
    }).catch(err => {

      app.showInfo(err.toString());
      that.setData({
        hiddenLoading: true
      })
    })
  },
  // 获取优惠券列表
  getMyTickets() {
    const that = this;

    let tickets = [];
    let popup = [];
    Object.keys(that.data.orderData.couponNum).forEach((item, index) => {
      popup[index] = false
      let json = {
        token: app.globalData.token,
        goods_id: that.data.action == "buy_now" ? that.data.options.goodsid : "",
        goods_num: that.data.action == "buy_now" ? that.data.options.goodsnum : "",
        store_id: item,
        action: that.data.action
      }

      let jsonData = app.utils.getSignData(json)
      app.utils.post(app.api.reqUrls.getMyTickets, jsonData).then(res => {
        if (res.status == 1) {
          if (res.result && res.result.length === 0) {
            res.result.forEach(item => {
              item.state = false;
              item.use_start_time = app.moment(item.use_start_time * 1000).format('YYYY.MM.DD');
              item.use_end_time = app.moment(item.use_end_time * 1000).format('YYYY.MM.DD');
              item.money = item.money.split('.');
              item.condition = item.condition.split('.');
              item.platUsing = false;
            })
          }
          tickets[item] = res.result
          that.setData({
            tickets,
            popup
          })

          // let dataMain = {
          //   currentTarget: {
          //     dataset: {
          //       disabled: false,
          //       listindex: item,
          //       index: 0
          //     }
          //   }
          // }
          // that.chooseTicket(dataMain)
        } else {
          throw res.msg;
        }
      }).catch(err => {
        app.showInfo(err.toString())
      })
    })

  },
  //提交订单
  submitOrder() {
    const that = this;
    if (!this.data.orderData.addressList.address_id && that.data.sm == 0) {
      wx.showModal({
        showCancel: false,
        confirmColor: '#ec5300',
        content: '请选择收货地址',
        success(res) {
          if (res.confirm) {

          }
        }
      })
      return false
    }


    let submit = that.data.submit;
    if (submit == 1) {
      submit += 1;
      that.setData({
        submit: submit
      })
      setTimeout(() => {
        that.setData({
          submit: 1
        })
      }, 2000)
      let cart_form_data = {
        user_note: that.data.user_note,
        coupon_id: that.data.coupon_id
      }

      let comid = 0
      let json = {
        token: app.globalData.token,
        address_id: that.data.orderData.addressList.address_id,
        sm: that.data.sm,
        cart_form_data: JSON.stringify(cart_form_data),
        action: that.data.action,
        goods_id: that.data.action == "buy_now" ? that.data.options.goodsid : "",
        goods_num: that.data.action == "buy_now" ? that.data.options.goodsnum : "",
        act: "submit_order",
        type: "miniapp",
        com_id: comid,
      }

      let jsonData = app.utils.getSignData(json);
      that.setData({
        hiddenLoading: false
      })
      app.utils.post(app.api.reqUrls.submitOrder, jsonData).then(res => {
        if (res.status == 1) {
          let json2 = {
            token: app.globalData.token,
            trade_type: "JSAPI",
            master_order_sn: res.result,
            account: that.data.computeData.order_amount
          }
          let jsonData2 = app.utils.getSignData(json2);
          // 判断是余额支付还是微信支付。0是余额支付
          if (that.data.computeData.order_amount == 0) {
            wx.showModal({
              content: '下单成功',
              showCancel: false,
              confirmText: '我知道了',
              confirmColor: '#ff5151',
              success(e) {
                if (e.confirm) {
                  that.setData({
                    isPaid: true
                  })
                  wx.navigateBack({
                    delta: -1,
                    success() {

                      wx.navigateTo({
                        url: `/page/detail/pages/myOrder/myOrder?where=2`,
                      })
                    }
                  })
                }
              }
            })
            return {
              status: -999
            }
          } else {
            return app.utils.post(app.api.reqUrls.doPay, jsonData2) // 请求支付接口
          }
        } else if (res.status == -6) {
          wx.showModal({
            content: res.msg,
            confirmText: '我知道了',
            confirmColor: '#ff5151',
            showCancel: false,
            success(e) {
              if (e.confirm) {
                wx.navigateTo({
                  url: `/page/detail/pages/setPassword/setPassword?where=fillOrder`,
                })
              }
            }
          })
          return {
            status: -999
          }
        } else if (res.status == -11) {
          wx.showModal({
            content: res.msg,
            confirmText: '确定',
            confirmColor: '#ff5151',
            success(e) {
              if (e.confirm) {
                wx.navigateTo({
                  url: `/page/detail/pages/addresslist/addresslist?where=fillOrder`,
                })
              }
            }
          })
          return {
            status: -999
          }
        } else {
          throw res.msg
        }
      }).then(res => {
        if (res.status == -999) {
          that.setData({
            hiddenLoading: true
          })
          return false;
        }
        if (res.status == 1) {
          let preOrderId = res.result.pre_order
          let merchantId = res.result.ls_merchant_id
          let opAppId = res.result.open_appid
          wx.openEmbeddedMiniProgram({
            appId: opAppId, // 你要打开的小程序appid
            extraData: { //给B小程序传的参数
              autoPay: 1,
            },
            path: `pages/plugin/pay?preOrderId=${preOrderId}&merchantId=${merchantId}`, // 打开的页面路径，如果为空则打开首页
            envVersion: 'release', // 要打开的小程序版本 develop 开发版 trial 体验版 release 正式版
            success(resData) {
              console.log(resData, 11111)
              // 打开成功

              var listener = (props) => {
                console.log(props, 111)
                console.log(props.referrerInfo, 222)
                console.log(props.referrerInfo.extraData, 333)
                if (!props.referrerInfo.hasOwnProperty('extraData')) {
                  console.log('错误')
                  wx.navigateBack({
                    delta: -1,
                    success() {
                      setTimeout(() => {
                        wx.navigateTo({
                          url: `/page/detail/pages/myOrder/myOrder?where=0`,
                        })
                      }, 500)
                    }
                  })
                  console.log(1234)
                  if (listener) {
                    console.log(4567)
                    wx.offAppShow(listener)
                  }
                }
                if (props.referrerInfo.extraData.payStatus === '0') {
                  console.log('支付失败')
                  //支付失败
                  //.....
                  wx.showModal({
                    content: '付款失败',
                    showCancel: false,
                    confirmText: '我知道了',
                    confirmColor: '#ff5151',
                    success(e) {
                      if (e.confirm) {
                        wx.navigateBack({
                          delta: -1,
                          success() {
                            setTimeout(() => {
                              wx.navigateTo({
                                url: `/page/detail/pages/myOrder/myOrder?where=1`,
                              })
                            }, 500)
                          }
                        })
                      }
                    }
                  })
                }
                if (props.referrerInfo.extraData.payStatus === '1') {
                  console.log('支付成功')
                  //支付成功
                  //.....
                  wx.navigateBack({
                    delta: -1,
                    success() {
                      setTimeout(() => {
                        wx.navigateTo({
                          url: `/page/detail/pages/myOrder/myOrder?where=2`,
                        })
                      }, 500)
                    }
                  })
                }
                if (props.referrerInfo.extraData.payStatus === '3') {
                  console.log('用户取消支付')
                  //用户取消支付(订单状态流转为已关闭)
                  //......
                  wx.showModal({
                    content: '付款失败',
                    showCancel: false,
                    confirmText: '我知道了',
                    confirmColor: '#ff5151',
                    success(e) {
                      if (e.confirm) {
                        wx.navigateBack({
                          delta: -1,
                          success() {
                            setTimeout(() => {
                              wx.navigateTo({
                                url: `/page/detail/pages/myOrder/myOrder?where=1`,
                              })
                            }, 500)
                          }
                        })
                      }
                    }
                  })
                }
                console.log(123)
                if (listener) {
                  console.log(456)
                  wx.offAppShow(listener)
                }
              };
              wx.onAppShow(listener)
            },
            fail(e) {
              console.log(e, 999999)
              // 打开失败
            },
          })
          // wx.requestPayment({ // 调取支付
          //   timeStamp: res.result.timeStamp.toString(),
          //   nonceStr: res.result.nonceStr,
          //   package: res.result.package,
          //   signType: res.result.signType,
          //   paySign: res.result.sign,
          //   success(res) {
          //     if (res.errMsg == "requestPayment:ok") {
          //       that.setData({
          //         hiddenLoading: true,
          //         isPaid: true
          //       })
          //       app.getInfo(app.globalData.token);
          //       wx.navigateBack({
          //         delta: -1,
          //         success() {
          //           setTimeout(() => {
          //             wx.navigateTo({
          //               url: `/page/detail/pages/myOrder/myOrder?where=2`,
          //             })
          //           }, 500)
          //         }
          //       })
          //     } else {
          //       throw res.errMsg;
          //     }
          //   },
          //   fail(res) {
          //     that.setData({
          //       hiddenLoading: true
          //     })
          //     wx.showModal({
          //       content: '付款失败',
          //       showCancel: false,
          //       confirmText: '我知道了',
          //       confirmColor: '#ff5151',
          //       success(e) {
          //         if (e.confirm) {
          //           wx.navigateBack({
          //             delta: -1,
          //             success() {
          //               setTimeout(() => {
          //                 wx.navigateTo({
          //                   url: `/page/detail/pages/myOrder/myOrder?where=1`,
          //                 })
          //               }, 500)
          //             }
          //           })
          //         }
          //       }
          //     })
          //   }
          // })

        } else {
          throw res.msg
        }
      }).catch(err => {
        app.showInfo(err.toString())
        that.setData({
          hiddenLoading: true,
          isPaid: false
        })
      })
    }



  },

  // 获取备注信息
  getNote(e) {
    const that = this;
    let id = e.currentTarget.dataset.storeid;
    let user_note = that.data.user_note;
    user_note[id] = e.detail.value;
    that.setData({
      user_note,
    })
  },

  // 选择优惠券
  chooseTicket(e) {
    const that = this;
    let disabled = e.currentTarget.dataset.disabled;
    let listIndex = e.currentTarget.dataset.listindex;
    let index = e.currentTarget.dataset.index;
    if (disabled) {
      return
    }

    // 选择优惠券唯一
    if (!that.data.tickets[listIndex][index].state) {
      that.data.tickets[listIndex].forEach(item => {
        item.state = false
      })
      that.data.tickets[listIndex][index].state = true
      that.setData({
        tickets: that.data.tickets
      })
    } else {
      that.data.tickets[listIndex][index].state = false
      that.setData({
        tickets: that.data.tickets
      })
    }

    that.data.tickets.forEach((item, i) => {
      item.forEach((data, j) => {
        if (data.is_plat == 1 && listIndex != i) {
          if (that.data.tickets[listIndex][index].cid == data.cid) {
            data.platUsing = true;
          } else {
            data.platUsing = false;
          }
        }
      })
    })

    if (!that.data.tickets[listIndex][index].state && that.data.tickets[listIndex][index].is_plat == 1) {
      that.data.tickets.forEach((item, i) => {
        item.forEach((data, j) => {
          if (data.is_plat == 1 && listIndex != i && that.data.tickets[listIndex][index].cid == data.cid) {
            data.platUsing = false;
          }
        })
      })
    }

    that.setData({
      tickets: that.data.tickets
    })

    if (that.data.tickets[listIndex] != null && that.data.tickets[listIndex] != []) {
      let arr = that.data.tickets[listIndex].filter(item => {
        return item.state
      })

      let coupon_id = that.data.coupon_id;
      let key = listIndex;
      if (arr.length == 0) {
        coupon_id[key] = 0;
      } else {
        arr.forEach(i => {
          let key = listIndex;
          let value = i.id;
          coupon_id[key] = value;
        })
      }
      that.setData({
        [`ticketsUsingCount[${listIndex}]`]: arr.length,
        coupon_id
      })
      that.getCompute();
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    that.setData({
      userInfo: app.globalData.userInfo,
      options
    })
    if (that.data.options.where == "cart") {
      that.setData({
        action: '',
      })
    }
  },

  onShow() {
    const that = this;
    let json = {
      address_id: app.globalData.addressId || '',
      token: app.globalData.token,
      goods_id: that.data.action == "buy_now" ? that.data.options.goodsid : "",
      goods_num: that.data.action == "buy_now" ? that.data.options.goodsnum : "",
      action: that.data.action,
    }
    let jsonData = app.utils.getSignData(json);
    // cart2  购物车
    app.utils.post(app.api.reqUrls.buyNow, jsonData).then(res => {
      that.setData({
        hiddenLoading: true
      })
      if (res.status == 1) {
        if (that.data.iseduitadd) {
          that.setData({
            [`orderData.addressList`]: res.result.addressList,
          });
        }
        let total_weight = 0;
        res.result.storeShippingCartList.forEach(item => {
          app.getImg(item.cartList) // 获取缩略图
          total_weight += item.store_goods_weight; // 计算总重量
        })
        res.result.total_weight = total_weight;

        // 检查是否所有店铺都免运费
        let isFreeSend = res.result.storeShippingCartList.every(item => {
          return item.store_goods_price >= item.store_free_price
        })
        // 自提和配送按钮是否展示
        if (res.result.or_hide_self_recieve == 0 && res.result.or_hide_delivery == 0) {
          that.setData({
            sm: 0,
            [`getGoodsTypes[1].checked`]: false,
            [`getGoodsTypes[0].checked`]: true
          })
        } else if (res.result.or_hide_self_recieve == 1 && res.result.or_hide_delivery == 0) {
          that.setData({
            sm: 0,
            [`getGoodsTypes[1].checked`]: false,
            [`getGoodsTypes[0].checked`]: true
          })
        } else if (res.result.or_hide_self_recieve == 0 && res.result.or_hide_delivery == 1) {
          that.setData({
            sm: 1,
            [`getGoodsTypes[0].checked`]: false,
            [`getGoodsTypes[1].checked`]: true
          })
        }
        that.setData({
          orderData: res.result,
          isFreeSend,
          [`getGoodsTypes[1].isShow`]: res.result.or_hide_self_recieve == 0 ? true : false,
          [`getGoodsTypes[0].isShow`]: res.result.or_hide_delivery == 0 ? true : false
        })

        that.getMyTickets();
        that.getCompute();

      } else {
        throw res.msg;
      }
    }).catch(err => {
      that.setData({
        hiddenLoading: true
      })
      // wx.showModal({
      //   content: err.toString(),
      //   showCancel: false,
      //   confirmText: "我知道了",
      //   confirmColor: "#eb3223",
      //   success() {
      //     wx.navigateBack({
      //       delta: -1
      //     })
      //   }
      // })
    })

  },

  onHide() {
    const that = this;
    that.setData({
      hiddenLoading: true
    })
  },
  // 判断姓名中是否有表情
  hasSpecial(substring) {
    if (substring) {
      // 判断是否有表情
      var reg = /[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF][\u200D|\uFE0F]|[\uD83C|\uD83D|\uD83E][\uDC00-\uDFFF]|[0-9|*|#]\uFE0F\u20E3|[0-9|#]\u20E3|[\u203C-\u3299]\uFE0F\u200D|[\u203C-\u3299]\uFE0F|[\u2122-\u2B55]|\u303D|[\A9|\AE]\u3030|\uA9|\uAE|\u3030/ig
      if (reg.test(substring)) {
        return true;
      }
      // 判断是否有特殊字符
      // var regs = /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/;
      var regs = /^.*$/
      if (!regs.test(substring)) {
        return true;
      }
    }
  },
})